package com.wnhz.work.yz.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.ServiceRecycleAdapter;
import com.wnhz.work.yz.view.SkillBookPop;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者： zxb
 * 日期： 2016/12/28
 * 描述： 售后
 */
public class CustomerServiceActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {
    private final static int ACTIVITY_RESULT_FOR_UPDATE = 101;
    private static final String TAG = "CustomerServiceActivity";

    private TextView tv_numbers;
    private TextView tv_service_type;
    private EditText et_service_message;
    private RecyclerView rc_service_images;
    private List<String> imageLists = new ArrayList<>();
    private ServiceRecycleAdapter mAdapter;

    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code
    public static final int CROP_IMG = 120;

    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    private static final String FilesPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youZhu/Compress/"; // 图片及其他数据保存文件夹
    private static File compressFile = new File(FilesPath);
    private static final String PhotePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youZhu/"; // 图片及其他数据保存文件夹
    private static File PhoteFilePath = new File(PhotePath);
    private static final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    private String saveCropImageFilePath;
    private String cropimagePath;

    private int num = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_service);

        initTitle();
        initData();
        initView();
    }

    private void initData() {

        imageLists.add(R.mipmap.ic_tianjiatupian + "");

        saveCropImageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youZhu/CropImage/";
        File folder = new File(saveCropImageFilePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }


    private TextView title;

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("售后");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView tv_right = (TextView) findViewById(R.id.view_main_right_text);
        tv_right.setText("提交");
        tv_right.setTextColor(Color.parseColor("#008c99"));
        tv_right.setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_right).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
    }

    private void initView() {

        tv_numbers = (TextView) findViewById(R.id.tv_numbers);
        tv_service_type = (TextView) findViewById(R.id.tv_service_type);
        et_service_message = (EditText) findViewById(R.id.et_service_message);
        rc_service_images = (RecyclerView) findViewById(R.id.rc_service_images);

        findViewById(R.id.tv_reduce).setOnClickListener(this);
        findViewById(R.id.tv_add).setOnClickListener(this);
        findViewById(R.id.rl_service_type).setOnClickListener(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rc_service_images.setLayoutManager(manager);
        /**
         * ----adapter添加了点击，长按事件  TODO 需要根据需求修改
         */
        mAdapter = new ServiceRecycleAdapter(this, imageLists, this, this);
        rc_service_images.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            case R.id.btn_main_right:
                MyToast("提交");
                break;

            //减少商品数目
            case R.id.tv_reduce:
                if (num > 1) {
                    num -= 1;
                    tv_numbers.setText(num + "");
                } else {
                    MyToast("不能减了");
                }
                break;

            //增加商品数目
            case R.id.tv_add:
                num += 1;
                tv_numbers.setText(num + "");
                break;

            //售后类型
            case R.id.rl_service_type:
                MyToast("售后类型");
                break;

            //点击图片，添加或者展示
            case R.id.iv_rc_service:
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        //ActivityCompat.requestPermissions(AdminAccountActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CONTEXT_INCLUDE_CODE);
                        return;
                    } else {
                        //有权限
//                        Intent selectPhotoIntent = new Intent(this, SelectPhotoActivity.class);
//                        startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
                    }
                } else {
                    //6.0以下
//                    Intent selectPhotoIntent = new Intent(this, SelectPhotoActivity.class);
//                    startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
                }


                Integer index = (Integer) v.getTag();

                if (index == imageLists.size() - 1) {

                    if (imageLists.size() >= 7) {
                        MyToast("最多选择6张图片");
                        return;
                    }
                    //点击的不是最后一张，继续添加
                    showPopmenu(v);

                } else {
                    MyToast("点击了第" + index + "张图片");
                }
                break;

            default:
                break;
        }
    }

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }


    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:
                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    System.out.println("拍照的路径---" + imageName);
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    /**
                     * ---调用裁剪
                     */
                    startCropPhotoPicture(uri);


//                    /**
//                     * ---获取原图路径
//                     */
//                    String imagePath = AlbumImagePath.getPath(this, uri);
//                    System.out.println("imagePath**====www==" + imagePath);
//
//                    if (!compressFile.exists()) {
//                        compressFile = new File(FilesPath);
//                        compressFile.mkdirs();
//                    }

                    /**
                     * 压缩图片的方法~~
                     */
//                    String targetPath = compressFile.getAbsolutePath() +df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//                    updateImage(compressImage, uri, currentClick);

//                    updateImage(imagePath, uri);

                }
                break;

            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    /**
                     * ---调用裁剪
                     */
                    startCropPhotoPicture(uri);

//                    /**
//                     * ---获取原图路径
//                     */
//                    String imagePath = tempFile.getAbsolutePath();
//                    System.out.println("拍照的路径=====：" + imagePath);
//
//                    if (!compressFile.exists()) {
//                        compressFile = new File(FilesPath);
//                        compressFile.mkdirs();
//                    }
//                    File file = new File(imagePath);
//                    if (!file.exists()) {
//                        return;
//                    }

                    /**
                     * 压缩图片的方法~~
                     */
//                    String targetPath = compressFile.getAbsolutePath() + df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//
//                    updateImage(compressImage, uri, currentClick);

//                    updateImage(imagePath, uri);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            case CROP_IMG:

                updateImage(cropimagePath, null);
                break;

            default:
                break;
        }

    }


    /**
     * 去裁剪拍照的图片
     */
    private void startCropPhotoPicture(Uri uri) {
        try {
            Intent cropIntent = new Intent("com.android.camera.action.CROP");

            cropIntent.setDataAndType(uri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("return-data", true);
            // 构建裁剪后应该保存的文件名

            String time = System.currentTimeMillis() + "";

            cropimagePath = saveCropImageFilePath + time + ".jpg";

            Log.i(TAG, "startCropPhotoPicture: cropimagePath==" + cropimagePath);

            File file = new File(cropimagePath);
            if (file.exists()) {
                file.delete();
            }

            // 生成该文件，然后把该文件的Urine传进去，这样如果裁剪成功别切保存的话，那么就会把裁剪后的图片保存在该文件
            cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(cropimagePath)));
            startActivityForResult(cropIntent, CROP_IMG);
        } catch (Exception e) {
            Toast.makeText(CustomerServiceActivity.this, "您的手机不支持裁剪功能！", Toast.LENGTH_SHORT).show();

        }
    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }
        imageLists.add(0, imagePath);
        mAdapter.notifyDataSetChanged();
        System.out.println("===修改的imagePath===" + imagePath);


    }


    @Override
    public boolean onLongClick(View v) {
        final Integer index = (Integer) v.getTag();

        System.out.println("index:===" + index);
        /**
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("是否确认删除？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                imageLists.remove(imageLists.get(index));
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.show();

        return true;
    }

    //回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case CONTEXT_INCLUDE_CODE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
                } else if (grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    MyToast("很遗憾你把访问sd卡权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
                } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//                    Intent selectPhotoIntent = new Intent(this, SelectPhotoActivity.class);
//                    startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


}
